package cn.wolfcode.ssm.util;

import javax.servlet.http.HttpServletRequest;

public class IPUtils {

        private static final String ERRORIP = "127.0.0.1";

        public static String getIP(HttpServletRequest request){

            String IP = request.getHeader("X-Real-IP");

            if (IP == null || IP.length() == 0 || "unknow".equalsIgnoreCase(IP)){
                IP = request.getHeader("x-forwarded-for");
            }

            if (IP == null || IP.length() == 0 || "unknow".equalsIgnoreCase(IP)){
                IP = request.getRemoteAddr();
                //0:0:0:0:0:0:0:1是IPv6的地址，相当于IPv4的127.0.0.1
                if ("0:0:0:0:0:0:0:1".equals(IP)) {
                    IP = ERRORIP;
                }
            }

            if (IP == null || IP.length() == 0 || "unknow".equalsIgnoreCase(IP)){
                IP = ERRORIP;
            }

            int pos = IP.indexOf(',');
            if (pos >= 0){
                IP = IP.substring(0,pos);
            }

            return IP;
        }
    }
